package com.wdd.common.auth;

import com.wdd.common.utils.DateTimeUtil;
import com.wdd.recoveryvehicle.loginUser.bean.LoginPermissionVB;
import com.wdd.recoveryvehicle.loginUser.bean.LoginRolesVB;
import com.wdd.recoveryvehicle.loginUser.bean.LoginUserVB;
import com.wdd.recoveryvehicle.sysToken.bean.SysToken;
import com.wdd.recoveryvehicle.loginUser.service.LoginUserService;
import com.wdd.recoveryvehicle.sysToken.service.SysTokenService;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * shiro 自定义 的 realm
 * @globalMr
 */
@Component
public class AuthRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(AuthRealm.class);

    @Autowired
    private LoginUserService loginUserService;
    @Autowired
    private SysTokenService sysTokenService;

    /**
     * 获取用户的角色 和 权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1. 从 PrincipalCollection 中来获取登录用户的信息
        logger.info("获取用户的角色 和 权限");
        LoginUserVB loginUser = (LoginUserVB) principals.getPrimaryPrincipal();
        String user_nickname = loginUser.getUser_nickname();
        LoginUserVB loginUserVB = loginUserService.selectLoginUserVBByUserNickname(user_nickname);
        //Integer userId = user.getUserId();
        //2.添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (LoginRolesVB rolesVB : loginUserVB.getLoginRolesVBS()) {
            //2.1添加角色
            simpleAuthorizationInfo.addRole(rolesVB.getRole_name());
            for (LoginPermissionVB permissionVB : rolesVB.getLoginPermissionVBS()) {
                //2.1.1添加权限
                simpleAuthorizationInfo.addStringPermission(permissionVB.getPermission_name());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 验证 token 的有效性
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("验证 token 的有效性");
        //获取token，既前端传入的token
        String accessToken = (String) token.getPrincipal();
        SysToken tokenEntity = sysTokenService.selectSysTokenByToken(accessToken);
        //2. token失效
        if (tokenEntity == null || DateTimeUtil.strToDate8(tokenEntity.getExpire_time()).getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        //3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
        LoginUserVB user = loginUserService.selectLoginUserVBByUserId(tokenEntity.getUser_id());
        //4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
        if (user == null) {
            throw new UnknownAccountException("用户不存在!");
        }
        //5. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, this.getName());
        return info;
    }

}
